<?php
include 'class.twitter.php';
include 'config.php';

echo '<pre>';

$t = new twitter();
$t->username = 'chrisrauh';
$t->password = 'computer';
$t->type = 'xml';

//insertFriendsTimeline($t);
insertReplies($t);
println ("Done.");

echo '</pre>';

function insertFriendsTimeline($twitter, $numPages = 100) {
	
	println("Inserting friends timeline...");
	
	$page = 0;
	$xml = $twitter->friendsTimeline(false, false, false, 20, $page);
	
	if ($xml) {

		while (($xml->status) && ($page < $numPages)) {

			print ("Page " . $page . "\n");

			foreach ($xml->status as $status) {
				insertStatus($status);
			}

			$page++;
			$xml = $twitter->friendsTimeline(false, false, false, 20, $page);

		}

	}

}

function insertReplies($twitter, $numPages = 100) {
	
	println("Inserting replies...");

	$page = 0;
	$xml = $twitter->getReplies($page);
	
	if ($xml) {

		while (($xml->status) && ($page < $numPages)) {

			print ("Page " . $page . "\n");

			foreach ($xml->status as $status) {
				insertStatus($status);
			}

			$page++;
			$xml = $twitter->friendsTimeline($page);

		}

	}

}

function insertStatus($status) {
	
	//print_r($status);
	println($status->id . " - " . date("Y-m-d H:i", strtotime($status->created_at)) . " - " . $status->user->screen_name);
	flush();

	$q = "INSERT IGNORE INTO users ";
	$q .= "(id, screen_name, name, location, description, profile_image_url, url, protected, followers_count) ";
	$q .= "VALUES (%s,'%s','%s','%s','%s','%s','%s',%s, %s);";

	$q = sprintf($q, escapeDB($status->user->id), escapeDB($status->user->screen_name), escapeDB($status->user->name), escapeDB($status->user->location), escapeDB($status->user->description), escapeDB($status->user->profile_image_url), escapeDB($status->user->url), escapeDB($status->user->protected), escapeDB($status->user->followers_count));

	if (!mysql_query($q)) {
		$message = 'Invalid query: ' . mysql_error() . "\n";
		$message .= 'Whole query: ' . $query;
		die($message);
	}

	$q = "INSERT IGNORE INTO status ";
	$q .= "(id, created_at, text, source, truncated, in_reply_to_status_id, in_reply_to_user_id, favorited, ";
	$q .= "in_reply_to_screen_name, user_id) ";
	$q .= "VALUES (%s, '%s', '%s', '%s', %s, '%s', '%s', '%s', '%s', %s);";

	$q = sprintf($q, escapeDB($status->id), escapeDB(date("Y-m-d H:i", strtotime($status->created_at))), escapeDB($status->text), escapeDB($status->source), escapeDB($status->truncated), escapeDB($status->in_reply_to_status_id), escapeDB($status->in_reply_to_user_id), escapeDB($status->favorited), escapeDB($status->in_reply_to_screen_name), escapeDB($status->user->id));

	if (!mysql_query($q)) {
		$message = 'Invalid query: ' . mysql_error() . "\n";
		$message .= 'Whole query: ' . $query;
		die($message);
	}

}

function escapeDB($s) {
	return mysql_real_escape_string($s);
}

function println($s) {
	print ($s . "\n");
}

?>